package com.lagou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 访问次数过滤器，用于限制访问注册接口的次数
 */
@Component
public class AccessTimeFilter implements GlobalFilter, Ordered {
    /**
     * 最大访问次数
     */
    private final int MAX_ACCESS_TIMES = 10;

    /**
     * 统计的时间间隔，以毫秒为单位
     */
    private final long STAT_INTERVAL = 600000;

    /**
     * 记录访问注册接口的次数
     */
    private Map<String, AccessInfo> accessInfoMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断是否是访问注册接口
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        if (!path.startsWith("/api/user/register")) {
            return chain.filter(exchange);
        }

        // 更新访问记录
        String clientIp = request.getRemoteAddress().getHostString();
        AccessInfo accessInfo = updateAccessInfo(clientIp);

        // 判断访问次数是否超过上限
        AtomicInteger accessTimes = accessInfo.getAccessTimes();
        int value = accessTimes.addAndGet(1);

        if (value > MAX_ACCESS_TIMES) {
            return createRejectedResponse(exchange.getResponse());
        }

        return chain.filter(exchange);
    }

    /**
     * 创建拒绝响应
     *
     * @param response 响应对象
     * @return 创建结果
     */
    private Mono<Void> createRejectedResponse(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);

        String data = "Register too often!";
        DataBuffer buffer = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 创建访问记录
     *
     * @param clientIp 客户端IP
     * @return 访问记录
     */
    private AccessInfo createAccessInfo(String clientIp) {
        AccessInfo accessInfo = new AccessInfo();
        accessInfo.setAccessTimes(new AtomicInteger(0));
        accessInfo.setStartTime(System.currentTimeMillis());

        accessInfoMap.putIfAbsent(clientIp, accessInfo);
        return accessInfoMap.get(clientIp);
    }

    /**
     * 更新访问记录
     *
     * @param clientIp 客户端IP
     * @return 更新后的访问记录
     */
    private AccessInfo updateAccessInfo(String clientIp) {
        AccessInfo accessInfo = accessInfoMap.get(clientIp);
        if (accessInfo == null) {
            return createAccessInfo(clientIp);
        }

        // 判断是否超出统计区间
        long startTime = accessInfo.getStartTime();
        long curTime = System.currentTimeMillis();
        if (curTime < (startTime + STAT_INTERVAL)) {
            return accessInfo;
        }

        accessInfo.setAccessTimes(new AtomicInteger(0));
        accessInfo.setStartTime(System.currentTimeMillis());
        return accessInfo;
    }

    /**
     * 获取过滤器优先级
     *
     * @return 过滤器优先级
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
